package mongodb.general.operator.nodb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import mongodb.general.operator.config.base.ViewResult;
import mongodb.general.operator.nodb.services.CommMongoDBInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author YCWB0354
 * @since 2021/12/5 20:19:33
 */
@Validated
@RestController
@RequestMapping("commMongoDBInfo")
public class CommMongoDBInfoController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CommMongoDBInfoService commMongoDBInfoService;


    /**
     * 通用的查询接口
     *
     *{
     *   "data": {
     *     "tableName": "empty_collection",
     *     "age":23,
     *     "name":"张",
     *     "queryFuzzList":["name"]
     *   }
     * }
     *
     * @param infoDto Json格式查询条件
     * @return 查询结果
     */
    @PostMapping(value = "/getByParams")
    public ViewResult<List<Object>> getByParams(@RequestBody JSONObject infoDto) {
        logger.debug("通用的查询接口信息：" + JSON.toJSONString(infoDto));
        try {
            List<Object> resultInfo = commMongoDBInfoService.getByParams(infoDto.getJSONObject("data"));
            if(resultInfo == null || resultInfo.size() == 0){
                return ViewResult.success("没有满足查询条件的数据，请确认后再查询",resultInfo);
            }
            return ViewResult.success(resultInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ViewResult.error(e.getMessage(), new ArrayList<>());
        }
    }

    /**
     * 增加信息
     *
     * @param infoDto 保存对象
     * @return 是否添加成功
     */
    @PostMapping(value = "/insert")
    public ViewResult<Object> insert(@RequestBody JSONObject infoDto) {
        try {
            logger.debug("新增数据信息：" + JSON.toJSONString(infoDto));
            List<Object> returnList = new ArrayList<>();
            //单条数据得场合
            if (infoDto.get("data") instanceof Map) {
                JSONObject objectJson = infoDto.getJSONObject("data");
                try {
                    commMongoDBInfoService.insert(objectJson);
                } catch (Exception e) {
                    e.printStackTrace();
                    objectJson.put("resultInfo", e.getMessage());
                    returnList.add(objectJson);
                }
                //多条数据的场合
            } else if (infoDto.get("data") instanceof List) {
                JSONArray arrayJson = infoDto.getJSONArray("data");

                for (int i = 0; i < arrayJson.size(); i++) {
                    JSONObject objectData = arrayJson.getJSONObject(i);
                    try {
                        commMongoDBInfoService.insert(objectData);
                    } catch (Exception e) {
                        e.printStackTrace();
                        objectData.put("resultInfo", e.getMessage());
                        returnList.add(objectData);
                    }
                }
            }
            //没有数据的场合说明保存成功
            if (returnList == null || ((List) returnList).size() == 0) {
                return ViewResult.success(true);
            }
            return ViewResult.error("添加数据有失败", returnList);

        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            return ViewResult.error("数据添加失败失败,未知异常" + e.getMessage());
        }

    }


    /**
     * 更新信息
     *
     * @param infoDto 更新对象
     * @return 是否更新成功
     */
    @PostMapping(value = "/update")
    public ViewResult<Object> update(@RequestBody JSONObject infoDto) {
        try {
            List<Object> returnList = new ArrayList<>();
            logger.debug("更新信息信息：" + JSON.toJSONString(infoDto));
            if (infoDto.get("data") instanceof List) {
                JSONArray arrayJson = infoDto.getJSONArray("data");
                //List infoInner = (List) infoDto;
                for (int i=0;i<arrayJson.size();i++) {
                    JSONObject mapInfoDate = arrayJson.getJSONObject(i);
                    try {
                        commMongoDBInfoService.update(mapInfoDate);
                    } catch (Exception e) {
                        e.printStackTrace();
                        mapInfoDate.put("resultInfo", e.getMessage());
                        returnList.add(mapInfoDate);
                    }
                }

            } else {
                JSONObject mapInfoDate = infoDto.getJSONObject("data");
                try {
                    commMongoDBInfoService.update(mapInfoDate);
                } catch (Exception e) {
                    e.printStackTrace();
                    mapInfoDate.put("resultInfo", e.getMessage());
                    returnList.add(mapInfoDate);
                }
            }

            //没有数据的场合说明保存成功
            if (returnList == null || ((List) returnList).size() == 0) {
                return ViewResult.success("数据更新成功");
            }

            return ViewResult.error("更新数据有失败", returnList);

        } catch (Exception e) {
            e.printStackTrace();
            return ViewResult.error("数据更新失败" + e.getMessage());
        }

    }


    /**
     * 主键查询消息
     *
     * @param infoDto 查询对象
     * @return 是否查询成功
     */
    @PostMapping(value = "/getById")
    public ViewResult<Object> getById(@RequestBody JSONObject infoDto) {
        logger.debug("主键查询信息：" + JSON.toJSONString(infoDto));
        try {

            Object resultData = commMongoDBInfoService.getById(infoDto.getJSONObject("data"));
            if (resultData == null) {
                return ViewResult.error("查询失败，该Id不存在。");
            }
            return ViewResult.success(resultData);
        } catch (Exception e) {
            e.printStackTrace();
            return ViewResult.error("数据查询失败: " + e.getMessage());
        }

    }


    /**
     * 删除消息
     *
     * @param infoDto 删除对象
     * @return 是否删除成功
     */
    @PostMapping(value = "/remove")
    public ViewResult<Object> remove(@RequestBody JSONObject infoDto) {
        logger.debug("删除消息信息：" + JSON.toJSONString(infoDto));
        try {
            Object resultInfo = commMongoDBInfoService.remove(infoDto.getJSONObject("data"));
            return ViewResult.success(resultInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ViewResult.error("数据查询失败");
        }

    }


    /**
     * 分页查询
     *
     * @param infoDto Json格式查询条件
     * @return 查询结果
     */
    @PostMapping(value = "/page")
    public ViewResult<Page<Object>> page(@RequestBody JSONObject infoDto) {
        logger.debug("分页查询信息：" + JSON.toJSONString(infoDto));
        try {
            Page<Object> page = commMongoDBInfoService.page(infoDto.getJSONObject("data"));
            return ViewResult.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return ViewResult.error("数据查询失败" + e.getMessage());
        }
    }
}
